package main.controller;

import java.io.File;
import java.util.Observable;
import java.util.Observer;
import main.controller.MVCEvent.EventType;
import main.model.Factory;
import main.view.GEDIVAFrame;


/**
 * @author Yaqi Zhang
 *         This Control creates View and Model and allows View to pass either
 *         URL or
 *         File to load to Model and Model to pass data loaded to View.
 *
 */
public class GEDIVAController implements Observer {
    private final Factory myFactory;
    private final GEDIVAFrame myFrame;

    /**
     *
     */
    public GEDIVAController () {
        myFrame = new GEDIVAFrame("Frame", "English", this);
        myFactory = new Factory(this);
    }

    /**
     *
     * @param url 
     */
    public void loadModel (String url) {
        myFrame.setDataModel(myFactory.loadModel(url));
    }

    /**
     * 
     * @param fileToLoad 
     */
    public void loadModel(File fileToLoad) {
        myFrame.setDataModel(myFactory.loadModel(fileToLoad));
    }

    @Override
    public void update (Observable source, Object event) {
        // Not really doing MVC since view part isn't in the loop yet so to
        // speak. But here is basically where you catch things coming from
        // models, then take the appropriate action on the view and vice
        // versa
        if (event instanceof MVCEvent) {
            EventType type = ((MVCEvent) event).getType();
            Object msg = ((MVCEvent) event).getMessage();

            if (type == EventType.ERROR && (msg instanceof Exception || msg instanceof String)) {
                // For now just print to stderr (we should do something that's
                // view agnostic though)
                System.err.println(msg.toString());
            }

        }

        // NOTE: Currently Models and Builders send messages to the controller.
        // The view should be added sometime as well.
    }
}
